package com.sogo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Location;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/*This activity is executed after logon screen. Defaults to friends list*/
public class FriendsListMainScreen extends MapActivity implements
		OnTabChangeListener {

	private static final String FRIENDS_TAB_TAG = "Friends";
	private static final String MAP_TAB_TAG = "Map";
	private static final String REQUREST_TAG = "Requests";
	private static final String EVENT_TAG = "Events";
	public static long refreshRate = 240000;
	public static long oldRate = 240000;

	private TabHost tabHost;

	private ListView listView;
	private ListView listView2;
	private ListView listView3;
	private MapView mapView;
	MapController mc;
	GeoPoint p;
	public static LocationManager lm;
	public static LocationListener locationListener;
	private double longitude;
	private double latitude;
	ServerConnection serverConn = new ServerConnection();
	DBAdapter db = new DBAdapter(this);

	private String email;
	private String password;
	private String username;
	private String firstname;
	private String lastname;
	private static buddy[] friends;
	private static buddy[] requests;
	private static Events[] events;
	private int checked = 0;
	private Button btnCreateEvent;
	Bitmap[] bit = null;
	String[] url;
	private int oldRequests;
	private int newRequests;

	public List<Overlay> mapOverlays;
	public MyItemizedOverlay itemizedoverlay;
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	RowData rd;


	private Integer[] imgid = { R.drawable.androidguy, R.drawable.androidguy,
			R.drawable.androidguy, R.drawable.androidguy };

	Location bestLocation;

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.friendsmenu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int pos = info.position;
		switch (item.getItemId()) {
		case R.id.Delete:
			JSONArray jsonArray = null;
			JSONObject json = new JSONObject();
			String userID = db.getOwnID();
			String friendID = Integer.toString(friends[pos].userID);

			try {
				json.put("userID", userID);
				json.put("friendID", friendID);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jsonArray = ServerConnection.CommunicateWithServer(json, 7);// 0 for
			Context context = getApplicationContext();
			CharSequence text = "You deleted a friend, you bad person!";
			int duration = Toast.LENGTH_SHORT;

			Toast toast = Toast.makeText(context, text, duration);
			toast.show();
			return true;
			/*
			 * case R.id.delete: deleteNote(info.id); return true;
			 */
		case R.id.eventInvite:
        	userID=db.getOwnID();
        	final String friendID2=Integer.toString(friends[pos].userID);

        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setTitle("Invite to Event");
   	
        	
        	 JSONArray jsonArray2=null;
         	JSONObject json2 = new JSONObject();
             try {
     			json2.put("userID", userID);
     		} catch (JSONException e) {
     			// TODO Auto-generated catch block
     			e.printStackTrace();
     		}
             jsonArray2=ServerConnection.CommunicateWithServer(json2,10);
             int numOfRequests=0;
             String[] names2 = null;
             String[] friendIDs2=null;
             
             if(jsonArray2!=null) //found some requests
             {
     	        
     	        numOfRequests=jsonArray2.length();
     	        events=new Events[numOfRequests];
     	        names2=new String[numOfRequests];
     	        friendIDs2=new String[numOfRequests];
     	        
     	        try {
     				for(int i=0;i<numOfRequests;i++){
     					json2=jsonArray2.getJSONObject(i);
     					events[i] = new Events();
     					events[i].setValues(Integer.parseInt(json2.getString("EVENTID")),json2.getString("EVENTNAME")
     							,json2.getString("EVENTTIME"),json2.getString("EVENTLOCATION"),json2.getString("EVENTDECRIPTION"));
     					
     					
     				}
     	    	} catch (JSONException e) {
     	    		e.printStackTrace();
     			}
             }
             List<String> requestList=new ArrayList<String>();
             if(jsonArray2!=null)
     		{
     			for(int i=0;i<numOfRequests;i++)
     			{
     				requestList.add(events[i].Eventname);
     			
     			}
     		}
     		if(jsonArray2==null)
     		{
     			requestList.add("No events");
     		}
     		final CharSequence[] charSequenceItems = requestList.toArray(new CharSequence[requestList.size()]);
             
             
        	builder.setItems(charSequenceItems, new DialogInterface.OnClickListener() {
        	    public void onClick(DialogInterface dialog, int tester) {
        	    	JSONObject json = new JSONObject();
        	    	JSONArray jsonArray=null;
        	    	final String eventID=Integer.toString(events[tester].Eventid);
        	    	try {
        	    		json.put("friendID", friendID2);
        				json.put("eventID", eventID);
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        	    	jsonArray=ServerConnection.CommunicateWithServer(json,11);
        	    }
        	});
        	builder.setNegativeButton("Cancel",
		 			new DialogInterface.OnClickListener() {

		 			public void onClick(DialogInterface dialog, int which) {
		 				
		 			 }
		 			 });
        	AlertDialog alert = builder.create();
        	alert.show();
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
		setContentView(R.layout.map);
		
		Resources res = getResources();

		// GPS STUFF
		lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener();
		JSONArray jsonArray = null;
		
		startService(new Intent(this, AppService.class));

		JSONObject json = new JSONObject();
		String userID = db.getOwnID();
		String refreshTest = db.getRefreshRate();

		// setup map view
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.postInvalidate();

		mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(
				R.drawable.androidguy);
		itemizedoverlay = new MyItemizedOverlay(drawable, this);

		Context context = getApplicationContext();
		CharSequence text = "Current refresh rate: " + refreshTest;
		int duration = Toast.LENGTH_LONG;

		Toast toast = Toast.makeText(context, text, duration);
		// toast.show();

		try {
			json.put("userID", userID);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonArray = ServerConnection.CommunicateWithServer(json, 6);// 6 for get
																	// friends
																	// list
		int numOfFriends = 0;
		String[] names = null;
		String[] friendIDs = null;


		if (jsonArray != null) // found some friends
		{

			numOfFriends = jsonArray.length();
			friends = new buddy[numOfFriends];
			names = new String[numOfFriends];
			friendIDs = new String[numOfFriends];
			Bitmap bitmap = null;
			bit = new Bitmap[numOfFriends];
			url = new String[numOfFriends];
			try {
				for (int i = 0; i < numOfFriends; i++) {
					json = jsonArray.getJSONObject(i);
					names[i] = json.getString("FIRSTNAME") + " "
							+ json.getString("LASTNAME");
					friendIDs[i] = json.getString("ID");
					double lon = Double
							.parseDouble(json.getString("LONGITUDE"));
					double lat = Double.parseDouble(json.getString("LAT"));
					double lastSeen = Double.parseDouble(json.getString("8"));
					friends[i] = new buddy();
					friends[i].setValues(
							Integer.parseInt(json.getString("ID")),
							json.getString("FIRSTNAME") + " "
									+ json.getString("LASTNAME"), lat, lon,
							lastSeen);



					String userid=db.getOwnID();
					url[i]="http://www.suopensim.com/app/images/"+Integer.parseInt(json.getString("ID"))+".jpg";

					GeoPoint point = new GeoPoint((int) (int) (lat * 1E6),
							(int) (lon * 1E6));
					String last = "Last seen: ";
					int min = friends[i].lastSeenInMin();
					if (min < 60) {
						last += Integer.toString(min);
						last += " minute(s) ago";
					} else {
						last += Integer.toString(friends[i].lastSeenInHour());
						last += " hour(s) ago";
					}
					OverlayItem overlayitem = new OverlayItem(point, names[i],
							last);
					itemizedoverlay.addOverlay(overlayitem);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		JSONArray jsonArray2 = null;
		JSONObject json2 = new JSONObject();
		try {
			json2.put("userID", userID);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonArray2 = ServerConnection.CommunicateWithServer(json2, 8);// 8 for
																		// requests
		int numOfRequests = 0;
		
		String[] names2 = null;
		String[] friendIDs2 = null;

		if (jsonArray2 != null) // found some requests
		{

			numOfRequests = jsonArray2.length();
			oldRequests = numOfRequests;
			requests = new buddy[numOfRequests];
			names2 = new String[numOfRequests];
			friendIDs2 = new String[numOfRequests];

			try {
				for (int i = 0; i < numOfRequests; i++) {
					json2 = jsonArray2.getJSONObject(i);
					names2[i] = json2.getString("FIRSTNAME") + " "
							+ json2.getString("LASTNAME");
					friendIDs2[i] = json2.getString("ID");
					requests[i] = new buddy();
					requests[i].setValues(
							Integer.parseInt(json2.getString("ID")),
							json2.getString("FIRSTNAME") + " "
									+ json2.getString("LASTNAME"), 1, 1, 0);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		JSONArray jsonArray3=null;
    	JSONObject json3 = new JSONObject();
        try {
			json3.put("userID", userID);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        jsonArray3=ServerConnection.CommunicateWithServer(json3,10);
        int numOfEvents=0;
          
        if(jsonArray3!=null) //found some requests
        {
        	numOfEvents=jsonArray3.length();
  	        events=new Events[numOfEvents];
  	        names2=new String[numOfEvents];
  	        friendIDs2=new String[numOfEvents];
  	        
  	        try {
  				for(int i=0;i<numOfEvents;i++){
  					json3=jsonArray3.getJSONObject(i);
  					events[i] = new Events();
  					events[i].setValues(Integer.parseInt(json3.getString("EVENTID")),json3.getString("EVENTNAME")
  							,json3.getString("EVENTTIME"),json3.getString("EVENTLOCATION"),json3.getString("EVENTDECRIPTION"));	
  				}
  	    	} catch (JSONException e) {
  	    		e.printStackTrace();
  			}
        }

		tabHost = (TabHost) findViewById(android.R.id.tabhost);

		// setup must be called if you are not inflating the tabhost from XML
		tabHost.setup();
		tabHost.setOnTabChangedListener(this);

		// setup list view
		listView = (ListView) findViewById(R.id.list);
		listView.setEmptyView((TextView) findViewById(R.id.empty));

		listView2 = (ListView) findViewById(R.id.list2);
		listView2.setEmptyView((TextView) findViewById(R.id.empty2));

		listView3 = (ListView) findViewById(R.id.list3);
		listView3.setEmptyView((TextView) findViewById(R.id.empty3));

		List<String> pointsList = new ArrayList<String>();
		List<String> requestList = new ArrayList<String>();
		List<String> eventList = new ArrayList<String>();
		if (jsonArray != null) {
			for (int i = 0; i < numOfFriends; i++) {
				pointsList.add(friends[i].name);

			}
		}
		if (jsonArray == null) {
			pointsList.add("No friends");
		}

		if (jsonArray2 != null) {
			for (int i = 0; i < numOfRequests; i++) {
				requestList.add(requests[i].name);

			}
		}
		if (jsonArray2 == null) {
			requestList.add("No requests");
		}
		// requestList.add("HELLO USER");
		
		if(jsonArray3!=null)
	  	{
	  		for(int i=0;i<numOfEvents;i++)
	  		{
	  			eventList.add(events[i].Eventname);	
	  		}
	  	}
	        
	  	if(jsonArray3==null)
	  	{
	  		eventList.add("No events");
	  	}

		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		data = new Vector<RowData>();
		for (int i = 0; i < numOfFriends; i++) {

			try {
				rd = new RowData(i, friends[i].name);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			data.add(rd);
		}
		CustomAdapter adapter = new CustomAdapter(this, R.layout.modlist, R.id.pointsList, data);
		ListView list = (ListView) findViewById(R.id.list);
		list.setTextFilterEnabled(true);
		list.setAdapter(adapter);

		// listView.setAdapter(new ArrayAdapter(this,
		// android.R.layout.simple_list_item_1, pointsList));
		listView2.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, requestList));
		listView3.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, eventList));
		registerForContextMenu(listView);
		registerForContextMenu(listView2);
		//registerForContextMenu(listView3);

		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {

				reDraw();
				if (friends[position].lat == 90
						&& friends[position].longtitude == 0) {
					Toast.makeText(getApplicationContext(),
							"No recent location data for that friend",
							Toast.LENGTH_SHORT).show();
				} else {
					GeoPoint geo = new GeoPoint(
							(int) (int) (friends[position].lat * 1E6),
							(int) (friends[position].longtitude * 1E6));
					setMapZoomPoint(geo, 35);
					tabHost.setCurrentTab(3);
				}

			}
		});
		/*
		 * Approve of request when user clicks on them.
		 */
		listView2.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				String userID = db.getOwnID();
				JSONObject friendJSON = new JSONObject();
				try {
					friendJSON.put("friendID", requests[position].userID);
					friendJSON.put("userID", userID);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// friendID);
				ServerConnection.CommunicateWithServer(friendJSON, 3);
				Intent intent = getIntent();
				finish();
				startActivity(intent);

			}
		});
		btnCreateEvent = (Button) findViewById(R.id.submitprofileButton);
		btnCreateEvent.setOnClickListener(new OnClickListener() {

			// @Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClassName("com.sogo", "com.sogo.CreateEvent");
				startActivity(i);
			}
		});
		final Context contextual=this;
		listView3.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(contextual);
				builder.setTitle("Event");
				builder.setMessage("Event Name: " + events[position].Eventname + '\n' + "Event Time: " + events[position].Eventtime + '\n'
						+ "Event Location: " + events[position].Eventlocation + '\n' + "Event Description: " + events[position].Eventdescription);
				
				AlertDialog alert = builder.create();
	        	alert.show();

			}
			});

		tabHost.addTab(tabHost.newTabSpec(FRIENDS_TAB_TAG)
				.setIndicator("Friends",res.getDrawable(R.drawable.ic_tab_friends)).setContent(R.id.main));
		tabHost.addTab(tabHost.newTabSpec(REQUREST_TAG)
				.setIndicator("Requests",res.getDrawable(R.drawable.ic_tab_request)).setContent(R.id.test));
		tabHost.addTab(tabHost.newTabSpec(EVENT_TAG).setIndicator("Events",res.getDrawable(R.drawable.ic_tab_events))
				.setContent(R.id.test2));

		// add views to tab host
		/*
		 * tabHost.addTab(tabHost.newTabSpec(FRIENDS_TAB_TAG).setIndicator("Friends"
		 * ).setContent(new TabContentFactory() { public View
		 * createTabContent(String arg0) { return listView; } }));
		 * tabHost.addTab
		 * (tabHost.newTabSpec(REQUREST_TAG).setIndicator("Requests"
		 * ).setContent(new TabContentFactory() { public View
		 * createTabContent(String arg0) { return listView2; } }));
		 * tabHost.addTab
		 * (tabHost.newTabSpec(EVENT_TAG).setIndicator("Events").setContent(new
		 * TabContentFactory() { public View createTabContent(String arg0) {
		 * return listView3; } }));
		 */
		tabHost.addTab(tabHost.newTabSpec(MAP_TAB_TAG).setIndicator("Map",res.getDrawable(R.drawable.ic_tab_map))
				.setContent(new TabContentFactory() {
					public View createTabContent(String arg0) {
						return mapView;
					}
				}));

		// allows the list view to show up first,
		// otherwise the mapview would be bleeding through and visible
		tabHost.setCurrentTab(3);
		tabHost.setCurrentTab(2);
		tabHost.setCurrentTab(1);
		tabHost.setCurrentTab(0);

		locationRequest();

		mapOverlays.add(itemizedoverlay);

	}

	/**
	 * Instructs the map view to navigate to the point and zoom level specified.
	 * 
	 * @param geoPoint
	 * @param zoomLevel
	 */
	private void setMapZoomPoint(GeoPoint geoPoint, int zoomLevel) {
		mapView.getController().setCenter(geoPoint);
		mapView.getController().setZoom(zoomLevel);
		mapView.postInvalidate();
	}

	protected boolean isRouteDisplayed() {
		return false;
	}

	/**
	 * Implement logic here when a tab is selected
	 */
	public void onTabChanged(String tabName) {
		if (tabName.equals(MAP_TAB_TAG)) {
			// do something on the map
		} else if (tabName.equals(FRIENDS_TAB_TAG)) {
			// do something on the list
		}
	}

	// GPS STUFF

	public class MyLocationListener implements LocationListener {

		// @Override
		public void onLocationChanged(Location loc) {

			if (bestLocation == null) {
				bestLocation = loc;
			} else if ((loc.getAccuracy() - bestLocation.getAccuracy()) < 0) {
				bestLocation = loc;
			}

			if (bestLocation != null) {
				Toast.makeText(
						getBaseContext(),
						"Lat: " + bestLocation.getLatitude() + " Lng: "
								+ bestLocation.getLongitude(),
						Toast.LENGTH_SHORT).show();
			}
			longitude = bestLocation.getLongitude();
			latitude = bestLocation.getLatitude();

			db.open();
			Cursor c = db.getUser();
			if (c.moveToFirst()) {
				username = c.getString(1);
				firstname = c.getString(2);
				lastname = c.getString(3);
				email = c.getString(4);
				password = c.getString(5);
			}
			db.close();
			int hidden = Integer.parseInt(db.getEnableLocation());
			if (hidden == 0) {
				longitude = 0.00;
				latitude = 90.00;
			}
			JSONObject json = new JSONObject();
			try {
				json.put("Username", username);
				json.put("Longitude", longitude);
				json.put("Latitude", latitude);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			ServerConnection.CommunicateWithServer(json, 4);
			Context context = getApplicationContext();
			CharSequence text = "update to server!";
			int duration = Toast.LENGTH_LONG;

			Toast toast = Toast.makeText(context, text, duration);
			// toast.show();
			GeoPoint geo = new GeoPoint(
					(int) (int) (bestLocation.getLatitude() * 1E6),
					(int) (bestLocation.getLongitude() * 1E6));
			setMapZoomPoint(geo, 35);
			
			JSONArray jsonArray = null;
			JSONObject jsonrequest = new JSONObject();
			String userID = db.getOwnID();
			try {
				jsonrequest.put("userID", userID);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jsonArray = ServerConnection.CommunicateWithServer(jsonrequest, 8);// 8 for
																			// requests

			if (jsonArray != null) // found some requests
			{
				newRequests = jsonArray.length();
			
				if(newRequests > oldRequests)
				{
					createNotification();
					oldRequests = newRequests;
				}
			}

		}

		// @Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(),

			"Gps Disabled",

			Toast.LENGTH_SHORT).show();
		}

		// @Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",

			Toast.LENGTH_SHORT).show();
		}

		// @Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exit:
			db.open();
			db.deleteDB();
			Intent k = new Intent();
			k.setClassName("com.sogo", "com.sogo.LoginRegistrationScreen");
			startActivity(k);
			stopService(new Intent(this, AppService.class));
			finish();
			return true;
		case R.id.setting:
			Intent i = new Intent();
			i.setClassName("com.sogo", "com.sogo.SettingMenu");
			startActivity(i);
			return true;
		case R.id.addfriend:
			Intent s = new Intent();
			s.setClassName("com.sogo", "com.sogo.SearchFriend");
			startActivity(s);
			return true;
		case R.id.refresh:
			reDraw();

		}
		return true;
	}

	public void reDraw() {
		mapView.getOverlays().clear();
		mapOverlays.clear();
		itemizedoverlay.clear();

		JSONArray jsonArray = null;

		JSONObject json = new JSONObject();
		String userID = db.getOwnID();
		String[] names = null;
		String[] friendIDs = null;

		try {
			json.put("userID", userID);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonArray = ServerConnection.CommunicateWithServer(json, 6);// 6 for get
																	// friends
																	// list
		int numOfFriends = 0;

		if (jsonArray != null) // found some friends
		{

			numOfFriends = jsonArray.length();
			friends = new buddy[numOfFriends];
			names = new String[numOfFriends];
			friendIDs = new String[numOfFriends];

			try {
				for (int j = 0; j < numOfFriends; j++) {
					json = jsonArray.getJSONObject(j);
					names[j] = json.getString("FIRSTNAME") + " "
							+ json.getString("LASTNAME");
					friendIDs[j] = json.getString("ID");
					double lon = Double
							.parseDouble(json.getString("LONGITUDE"));
					double lat = Double.parseDouble(json.getString("LAT"));
					double lastSeen = Double.parseDouble(json.getString("8"));
					friends[j] = new buddy();
					friends[j].setValues(
							Integer.parseInt(json.getString("ID")),
							json.getString("FIRSTNAME") + " "
									+ json.getString("LASTNAME"), lat, lon,
							lastSeen);

					GeoPoint point = new GeoPoint((int) (int) (lat * 1E6),
							(int) (lon * 1E6));
					String last = "Last seen: ";
					int min = friends[j].lastSeenInMin();
					if (min < 60) {
						last += Integer.toString(min);
						last += " minute(s) ago";
					} else {
						last += Integer.toString(friends[j].lastSeenInHour());
						last += " hour(s) ago";
					}

					OverlayItem overlayitem = new OverlayItem(point, names[j],
							last);
					itemizedoverlay.addOverlay(overlayitem);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mapOverlays.add(itemizedoverlay);
			tabHost.setCurrentTab(0);
		}
		
		jsonArray = null;
		JSONObject jsonrequest = new JSONObject();
		try {
			jsonrequest.put("userID", userID);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonArray = ServerConnection.CommunicateWithServer(jsonrequest, 8);// 8 for
																		// requests

		if (jsonArray != null) // found some requests
		{
			newRequests = jsonArray.length();
		
			if(newRequests > oldRequests)
			{
				createNotification();
				oldRequests = newRequests;
			}
		}
	}
	
public static void locationRequest(){
		
		if (oldRate == refreshRate) {
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
					refreshRate, 5, locationListener);
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
					refreshRate, 5, locationListener);
		}
		if (oldRate != refreshRate) {
			lm.removeUpdates(locationListener);
			oldRate = refreshRate;
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
					refreshRate, 5, locationListener);
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
					refreshRate, 5, locationListener);
		}
		
		
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		lm.removeUpdates(locationListener);
	}

	private class RowData {
		protected int mId;
		protected String mPointsList;

		RowData(int id, String pointsList) {
			mId = id;
			mPointsList = pointsList;
		}

		@Override
		public String toString() {
			return mId + " " + mPointsList;
		}
	}

	private class CustomAdapter extends ArrayAdapter<RowData> {
		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<RowData> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			TextView title = null;
			TextView detail = null;
			LoaderImageView2 i11 = null;
			//LoaderImageView image = (LoaderImageView) findViewById(R.id.loaderImageView);
			RowData rowData = getItem(position);
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.modlist, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			holder = (ViewHolder) convertView.getTag();
			title = holder.gettitle();
			title.setText(rowData.mPointsList);

			i11 = holder.getImage();
			int code=0;
			//String url = "http://suopensim.com/app/images/" + userid+ ".jpg";
			String urlNoAvatar="http://suopensim.com/app/images/noavatar.png";
			/*
			Bitmap bitmap1 = BitmapFactory
					.decodeStream((InputStream) new URL(url).getContent());
			mImageView.setImageBitmap(bitmap1);*/
			
			 try {
			        HttpURLConnection.setFollowRedirects(false);
			        int Count = 1;
			        URL testURL;
			            testURL = new URL((url[rowData.mId]));
			            HttpURLConnection con = (HttpURLConnection) testURL.openConnection();
			            con.setRequestMethod("HEAD");
			            Log.e("RESPONCE", Integer.toString(con.getResponseCode()));
			            code=con.getResponseCode();
			    } catch (Exception e) {

			    }
				if(code!=404)
					i11.setImageDrawable(url[rowData.mId]);
				else if(code==404)
					i11.setImageDrawable(urlNoAvatar);
			
			
			return convertView;
		}

		private class ViewHolder {
			private View mRow;
			private TextView title = null;
			private TextView detail = null;
			private LoaderImageView2 i11 = null;

			public ViewHolder(View row) {
				mRow = row;
			}

			public TextView gettitle() {
				if (null == title) {
					title = (TextView) mRow.findViewById(R.id.pointsList);
				}
				return title;
			}

			public LoaderImageView2 getImage() {
				if (null == i11) {
					i11 = (LoaderImageView2) mRow.findViewById(R.id.loaderImageView2);
				}
				return i11;
			}
		}
	}
	
	public void createNotification() {
		NotificationManager notificationManager = (NotificationManager) 
					getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon,
				"SoGo Notification", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		Intent intent = new Intent(this, NotificationReceiver.class);
		PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
		notification.setLatestEventInfo(this, "SoGo Friend Request",
				"You have a pending Friend Request", activity);
		notification.number += 1;
		notificationManager.notify(0, notification);

	}

}
